


import { LOADING_SOURCE_CODE, NOT_BOOTSTRAPPED } from "../applications/app.helpers";

function flattenFnArray(fns){ // 将函数通过then链连接起来
    fns = Array.isArray(fns)?fns:[fns]
    return function(props){
        return fns.reduce((p, fn) => p.then(() => fn(props)), Promise.resolve());
    }
}

export async function toLoadPromise(app) { 
    if(app.loadPromise){ 
        return app.loadPromise
    }
    return (
        //缓存,保证app.loadApp不重复执行
        app.loadPromise = Promise.resolve().then(async()=>{
            app.status =  LOADING_SOURCE_CODE //加载资源
            let { bootstrap, mount, unmount } = await app.loadApp(app.customProps)//调用load函数拿到接入协议
            app.status = NOT_BOOTSTRAPPED //还没有启动过 
        
            // 将多个promise组合在一起 compose
            app.bootstrap = flattenFnArray(bootstrap)
            app.mount = flattenFnArray(mount)
            app.unmount = flattenFnArray(unmount)
            delete app.loadPromise
            return app
        })
    )
    
} 